var sevenCircle, tenCircle;
var curDot;
var bjPathLine, usaPathLine, hkPathLine, tbPathLine, krPathLine, jpPathLine;
var cloudLayer; // 云图
var typhoonDots = [];
var typhoonLine = [];	// 台风实际路径数组，可以是多条
var curTyphoonCodes = [];  // 当前的台风编码

var timmer; // 用于控制弹出气泡的定时器

$(document).ready(function() {
	net.htwater.GoogleMap.initialize();
	net.htwater.GoogleMap.addWarningLine();
	var date = new Date();
	net.htwater.Typhoon.getTyphoonList(date.getFullYear());
});

var setMapType = function(type) {
	if("map" == type) {
		map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
	} else if("satellite" == type) {
		map.setMapTypeId(google.maps.MapTypeId.HYBRID);
	} else {// terrain
		map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
	}
}

$.namespace("net.htwater.Typhoon");
net.htwater.Typhoon = {
	showCloud : function() {
		if("隐藏云层" == $("#showCloud").html()) {
			$("#showCloud").html("显示云层");
			if (null != cloudLayer)
				cloudLayer.setMap(null);
		} else {
			$("#showCloud").html("隐藏云层");
			if (null == cloudLayer) {
				cloudLayer = net.htwater.GoogleMap.addCloudLayer();
			} else {
				cloudLayer.setMap(map);
			}
		}
	},
	clearTyphoon : function() {
		if(null != typhoonDots)
			net.htwater.GoogleMap.clearOverlays(typhoonDots);
		// if(null != typhoonLine)
		for (var line in typhoonLine) {
			net.htwater.GoogleMap.cleanPolyLine(typhoonLine[line]);
		}
		if(null != sevenCircle)
			sevenCircle.setMap(null);
		if(null != tenCircle)
			tenCircle.setMap(null);
		if(null != bjPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(bjPathLine);
		}
		if(null != usaPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(usaPathLine);
		}
		if(null != hkPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(hkPathLine);
		}
		if(null != tbPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(tbPathLine);
		}
		// no korea
		// if(null != krPathLine) {
		// net.htwater.GoogleMap.cleanPolyLine(krPathLine);
		// }
		if(null != jpPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(jpPathLine);
		}
	},
	showList : function() {
		if("隐藏列表" == $("#showTyphoon").html()) {
			$("#showTyphoon").html("显示列表");
			$("#listDiv").css("display", "none");
		} else {
			$("#showTyphoon").html("隐藏列表");
			$("#listDiv").css("display", "block");
		}
	},
	yearSelect : function() {
		var year = $("#yearList").val();
		showLoading();
		net.htwater.Typhoon.getTyphoonList(year);
	},
	getTyphoonList : function(year) {
		$.ajax({
			type : "post",
			data : {
				year : year
			},
			dataType : "jsonp",
			jsonp : "callback",
			jsonpCallback : "b",
			// url : "public?/getTyphoonAllPathById",
			url : "getTyphoonListByYear!typhoon",
			success : function(json) {
				var date = new Date();
				for(var y = date.getFullYear(); y >= 2000; y--) {
					if(y == year) {
						$("#yearList").append('<option value="' + y + '" selected >' + y + '</option>');
					} else {
						$("#yearList").append('<option value="' + y + '">' + y + '</option>');
					}
				}
				$("#listDiv").remove();
				$("body").append(initIScroll);
				$("#listDiv").css("display", "block");
				$("#listTitle").css("display", "block");
				$("#listDiv").css("width", 130);
				$(".scroller").css("width", "90%");
				//$("#listTitle").css("top", 90);
				//$("#listDiv").css("top", 120);
				var listDivHeight = 42 * json.length;
				if(listDivHeight > 240) {
					listDivHeight = 240;
				}
				$("#listDiv").css("height", listDivHeight);
				$(json).each(function() {
					var li = '<li id="tf-' + this.typhooncode + '">>> ' + this.typhooncode + '</li>';
					$("#listItem").append(li);
				});
				$("#listDiv li").click(function() {
					var id = this.id;
					showLoading();
					net.htwater.Typhoon.getTyphoonPath(id.split("-")[1].substring(0, 4));
				});
				loadiScroll('listDiv');
				//$("#listDiv li").first().click();
				net.htwater.Typhoon.loadLatestTyphoon();
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				// alert(errorThrown);
			}
		});
	},
	// 最新的台风
	loadLatestTyphoon : function() {
		$.ajax({
			type : "post",
			dataType : "jsonp",
			jsonp : "callback",
			jsonpCallback : "a",
			url : "getCurrentTyphoons!typhoon",
			success : function(json) {
				for (var index in json) {
					if (index > 0) {
						setTimeout('net.htwater.Typhoon.getTyphoonPath('+json[index]+')' ,1000);
					} else {
						net.htwater.Typhoon.getTyphoonPath(json[index]);
					}
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				// alert(errorThrown);
			}
		});
	},
	getTyphoonPath : function(typhooncode) {
		$.ajax({
			type : "post",
			data : {
				typhooncode : typhooncode
			},
			dataType : "jsonp",
			jsonp : "callback",
			jsonpCallback : "a",
			// url : "public?/getTyphoonAllPathById",
			url : "getTyphoonAllPathById!typhoon",
			success : function(json) {
				hideLoading();
				// net.htwater.GoogleMap.clearOverlays(typhoonDots);
				// net.htwater.GoogleMap.cleanPolyLine(typhoonLine);
				if(null != sevenCircle)
					sevenCircle.setMap(null);
				if(null != tenCircle)
					tenCircle.setMap(null);
				var infowindow = new google.maps.InfoWindow();
				var dots = [];
				var latestJsonObj;
				$(json).each(function() {
					var myLatlng = new google.maps.LatLng(this.latitude, this.longitude);
					var windPower = this.wind_power;
					var image = 'images/dot_green.png';
					if(windPower > 14) {
						image = 'images/dot_red.png';
					} else if(windPower > 12) {
						image = 'images/dot_orange.png';
					} else if(windPower > 9) {
						image = 'images/dot_blue.png';
					} else {
						image = 'images/dot_green.png';
					}
					net.htwater.Typhoon.addTyphoonDot(image, infowindow, myLatlng, "[" + this.typhooncode, "]<br>时间：" + this.wind_time + "<br>风力：" + this.wind_power + "级,风速：" + this.wind_speed + "米/秒<br>方向：" + this.move_direction + ",气压：" + this.air_pressure + "百帕", typhoonDots, this);
					dots.push(myLatlng);
					map.panTo(myLatlng);
					latestJsonObj = this;
				});
				google.maps.event.addListener(infowindow, 'closeclick', function() {
					// var myLatlng = new google.maps.LatLng(29.875, 121.556830);
					// map.panTo(myLatlng);
					// map.setZoom(5);
				});
				// add polyline
				typhoonLine.push(net.htwater.GoogleMap.addPolyLine(dots));
				// add latest circle and preLine
				var zoom = map.getZoom();
				var latestDot = dots.pop();
				sevenCircle = net.htwater.GoogleMap.drawCircle(latestDot, 6000 / zoom * latestJsonObj.seven_wind, "orange");
				tenCircle = net.htwater.GoogleMap.drawCircle(latestDot, 6000 / zoom * latestJsonObj.ten_wind, "red");
				net.htwater.Typhoon.drawPreline(latestJsonObj);
				
				// 隐藏列表 
				$("#showTyphoon").html("显示列表");
				$("#listDiv").css("display", "none");
				// 显示名称
				$("#popinfo").css({"display": "block"});
				$("#popinfo").html('当前台风：' + json[0].typhooncode);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				// alert(errorThrown);
			}
		});
	},
	drawPreline : function(json) {
		// bjPathLine, usaPathLine, hkPathLine
		
		// @20121024 判断是否存在，否则往回退，直到找到
		if(null != bjPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(bjPathLine);
		}
		bjPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.bj_latitude_0, json.bj_longitude_0), new google.maps.LatLng(json.bj_latitude_24, json.bj_longitude_24), new google.maps.LatLng(json.bj_latitude_48, json.bj_longitude_48), new google.maps.LatLng(json.bj_latitude_72, json.bj_longitude_72), new google.maps.LatLng(json.bj_latitude_96, json.bj_longitude_96)], "red");

		if(null != usaPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(usaPathLine);
		}
		usaPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.usa_latitude_0, json.usa_longitude_0), new google.maps.LatLng(json.usa_latitude_24, json.usa_longitude_24), new google.maps.LatLng(json.usa_latitude_48, json.usa_longitude_48), new google.maps.LatLng(json.usa_latitude_72, json.usa_longitude_72), new google.maps.LatLng(json.usa_latitude_96, json.usa_longitude_96)], "black");

		if(null != hkPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(hkPathLine);
		}
		hkPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.hk_latitude_0, json.hk_longitude_0), new google.maps.LatLng(json.hk_latitude_24, json.hk_longitude_24), new google.maps.LatLng(json.hk_latitude_48, json.hk_longitude_48), new google.maps.LatLng(json.hk_latitude_72, json.hk_longitude_72), new google.maps.LatLng(json.hk_latitude_96, json.hk_longitude_96)], "yellow");
		// tbPathLine, krPathLine, jpPathLine
		if(null != tbPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(tbPathLine);
		}
		tbPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.tb_latitude_0, json.tb_longitude_0), new google.maps.LatLng(json.tb_latitude_24, json.tb_longitude_24), new google.maps.LatLng(json.tb_latitude_48, json.tb_longitude_48), new google.maps.LatLng(json.tb_latitude_72, json.tb_longitude_72), new google.maps.LatLng(json.tb_latitude_96, json.tb_longitude_96)], "#CCFFCC");
		// no korea
		// if(null != krPathLine) {
		// net.htwater.GoogleMap.cleanPolyLine(krPathLine);
		// }
		// krPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.kr_latitude_0, json.kr_longitude_0), new google.maps.LatLng(json.kr_latitude_24, json.kr_longitude_24), new google.maps.LatLng(json.kr_latitude_48, json.kr_longitude_48), new google.maps.LatLng(json.kr_latitude_72, json.kr_longitude_72), new google.maps.LatLng(json.kr_latitude_96, json.kr_longitude_96)], "blue");
		if(null != jpPathLine) {
			net.htwater.GoogleMap.cleanPolyLine(jpPathLine);
		}
		jpPathLine = net.htwater.Typhoon.addPreLine([new google.maps.LatLng(json.jp_latitude_0, json.jp_longitude_0), new google.maps.LatLng(json.jp_latitude_24, json.jp_longitude_24), new google.maps.LatLng(json.jp_latitude_48, json.jp_longitude_48), new google.maps.LatLng(json.jp_latitude_72, json.jp_longitude_72), new google.maps.LatLng(json.jp_latitude_96, json.jp_longitude_96)], "green");
	},
	addPreLine : function(locations, color) {
		// 过滤掉为0的经纬度
		for(var i = 0; i < locations.length; i++) {
			if(0 == locations[i].lat() || 0 == locations[i].lng()) {
				locations = locations.slice(0, i);
				break;
			}
		}
		var polyline = new google.maps.Polyline({
			path : locations,
			strokeColor : color,
			strokeOpacity : 0.5,
			strokeWeight : 2
		});
		polyline.setMap(map);
		return polyline;
	},
	addTyphoonDot : function(image, infowindow, location, title, contentString, markersArray, json) {
		var marker = new google.maps.Marker({
			position : location,
			map : map,
			title : title,
			icon : image
		});
		markersArray.push(marker);
		// set bubble layer
		contentString =  title + contentString;
		google.maps.event.addListener(marker, 'click', function() {
//			$("#popinfo").css({"display": "block"});
//			$("#popinfo").html(contentString);
//			clearTimeout(timmer);
//			timmer = window.setTimeout(function() {
//		    	map.panTo($("#popinfo").css("display", "none"));
//		    }, 16000);
			infowindow.setContent(contentString);
			infowindow.open(map, marker);
			map.panTo(marker.getPosition());
			map.setZoom(5);
			var zoom = map.getZoom();
			if(null != sevenCircle)
				sevenCircle.setMap(null);
			if(null != tenCircle)
				tenCircle.setMap(null);
			sevenCircle = net.htwater.GoogleMap.drawCircle(marker.getPosition(), 6000 / zoom * json.seven_wind, "orange");
			tenCircle = net.htwater.GoogleMap.drawCircle(marker.getPosition(), 6000 / zoom * json.ten_wind, "red");
			net.htwater.Typhoon.drawPreline(json);
		});
	},
}

var showLoading = function() {
//	if(null == loadingDlg)
//		loadingDlg = $.Zebra_Dialog('<strong>提示</strong>, 数据加载中，请耐心等待！');
}
var hideLoading = function() {
//	if(null != loadingDlg) {
//		loadingDlg.close();
//		loadingDlg = null;
//	}
}

var initIScroll = '<div id="listDiv" class="l3-menu-bg"><div class="scroller"><ul id="listItem"></ul></div>	</div>';
var hoverClassRegEx = new RegExp('(^|\\s)iScrollHover(\\s|$)');
function loadiScroll(container) {
	var myScroll = new iScroll(container, {
		onBeforeScrollStart : function(e) {
			var target = e.target;
			clearTimeout(this.hoverTimeout);
			while(target.nodeType != 1)
			target = target.parentNode;
			this.hoverTimeout = setTimeout(function() {
				if(!hoverClassRegEx.test(target.className))
					target.className = target.className ? target.className + ' iScrollHover' : 'iScrollHover';
			}, 80);
			this.hoverTarget = target;
			e.preventDefault();
		},
		onScrollMove : function() {
			if(this.hoverTarget) {
				clearTimeout(this.hoverTimeout);
				this.hoverTarget.className = this.hoverTarget.className.replace(hoverClassRegEx, '');
				this.target = null;
			}
		},
		onBeforeScrollEnd : function() {
			if(this.hoverTarget) {
				clearTimeout(this.hoverTimeout);
				this.hoverTarget.className = this.hoverTarget.className.replace(hoverClassRegEx, '');
				this.target = null;
			}
		}
	});
}